package echo.demo2;

import echo.protocol.MessageProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.ExecutorService;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    private final ExecutorService pool;

    public ServerHandler(ExecutorService pool) {
        this.pool = pool;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof MessageProtocol) {
            String s = new String(((MessageProtocol) msg).getContent(), CharsetUtil.UTF_8);
            String response = s + " server";
            MessageProtocol messageProtocol = new MessageProtocol(((MessageProtocol) msg).getReqId(), response.length(), response.getBytes(CharsetUtil.UTF_8));
            pool.submit(new Task(ctx, messageProtocol));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }

    static class Task implements Runnable{
        private ChannelHandlerContext ctx;
        private MessageProtocol messageProtocol;

        public Task(ChannelHandlerContext ctx, MessageProtocol messageProtocol) {
            this.ctx = ctx;
            this.messageProtocol = messageProtocol;
        }

        @Override
        public void run() {
            ctx.channel().writeAndFlush(messageProtocol);
        }
    }

    public static void main(String[] args) {
//        System.out.println(Arrays.toString("asffsd152".getBytes(CharsetUtil.UTF_8)));
    }
}
